import getFiledName from "@/utils/columnProp";

function setColumnParams(column, key, value) {
    if (value === undefined) {
        return;
    }
    if (!column['params']) {
        column['params'] = {};
    }
    column['params'][key] = value;
}

export const OTMixinColumnMethod = {
    methods: {
        setColumnCssClass(o) {
            if (o.dictCode) {
                let vals = this.dictVal(o.dictCode);
                let cssClass = {};
                if (vals) {
                    let dictValueLabel = {};
                    for (let obj of vals) {
                        dictValueLabel[obj.dictValue] = obj.dictLabel
                        if (obj.cssClass) {
                            let css = obj.cssClass.trim()
                            try {
                                css = css.replace(/([a-zA-Z_]\w*):/g, '"$1":').replace(/'/g, '"');
                                css = JSON.parse(css)
                                if (Array.isArray(css)) {
                                    let data = {};
                                    if (css[0]) {
                                        data['backgroundColor'] = css[0];
                                    }
                                    if (css[1]) {
                                        data['color'] = css[1];
                                    }
                                    cssClass[obj.dictValue] = data
                                } else {
                                    cssClass[obj.dictValue] = css
                                }
                            } catch (e) {
                                console.error("列名：", o.title, "数据字典：", obj.dictLabel, "样式异常：", css)
                            }
                        }
                    }
                    setColumnParams(o, 'dictValueLabel', dictValueLabel);
                }

                if (Object.keys(cssClass).length != 0) {
                    setColumnParams(o, 'cssClass', cssClass);
                }
            }
        }, initColumn(columns, tableConfig) {
            this.table.mergeFields = []
            let items = [];
            columns = columns.sort(({sort: a}, {sort: b}) => a - b);
            for (let column of columns) {
                this.toParseOtherProp(column);
            }
            this.table.columnSource = JSON.parse(JSON.stringify(columns))
            let {optionJson, seq} = tableConfig;
            if (optionJson) {
                optionJson = JSON.parse(optionJson);
            }
            for (let o of columns) {
                this.setColumnCssClass(o)
                this.initFormatter(o)
                this.initSlots(o);
                this.setTreeOpenColumn(o, tableConfig);
                this.setMergeField(o);
                this.setColumnShowOverFlow(o, optionJson);
                this.setProp(o);
                this.setColumnHide(o);
                this.setFixed(o);
                this.setShowFooter(o);
                this.getVNode(o, items);
            }
            items.sort(({searchSort: a}, {searchSort: b}) => a - b)
            this.setSearchArea(items);
            columns = this.initBodyLeftColumn(columns, seq);
            if (this.table['show-footer']) {
                if (!columns[0].width || columns[0].width < 55) {
                    columns[0].width = 55;
                }
            }
            this.table.columns = columns
            //暂时不合并，启用虚拟滚动
            this.initMergeCells();

        }, /**
         * 初始化列左边
         * @param columns
         * @param type
         * @returns {*}
         */
        initBodyLeftColumn(columns, type) {
            if (type == 1) {
                columns.unshift({type: 'seq', width: 55, title: '序号', fixed: 'left'});
            }
            if (this.selectBox == 2) {
                columns.unshift({type: 'checkbox', width: 45, showOverflow: false, fixed: 'left'});
            } else if (this.selectBox == 1) {
                columns.unshift({type: 'radio', width: 45, showOverflow: false, fixed: 'left'});
            }
            return columns;
        }, setTreeOpenColumn(o, tableConfig) {
            if (tableConfig.tree == 1 && o.field == tableConfig.openColumn) {
                o.treeNode = true
                if (!o.align) {
                    o.align = 'left'
                }
            }
        }, setMergeField(column) {
            if (column.mergeFlag == '1') {
                this.table.mergeFields.push(column.field)
            }
        }, setColumnHide(o) {
            //隐藏
            if (o.visible == "0") {
                o.visible = false;
            }
        }, initFormatter(o) {
            try {
                if (o.formatter) {
                    o.formatter = eval("({cellValue, row, column})=>{" + o.formatter + "}")
                } else if (o.dictCode) {
                    o.formatter = eval("" + "({cellValue, row, column})=>{if(column.params && column.params.dictValueLabel){ let dictValueLabelElement = column.params.dictValueLabel[cellValue];if(dictValueLabelElement){return dictValueLabelElement;} }return  cellValue}")
                }
            } catch (e) {
                console.log(o.title, "formatter异常：", o.formatter)
                this.$message.error(o.title + "formatter异常!")
            }
        }, initSlots(o) {
            if (o.selectDom == 20) {
                o.slotsName = 'img_default';
                o.slots = {
                    default: 'img_default'
                }
            }
            if (o.selectDom == '21') {
                o.slotsName = 'icon_default';
                o.slots = {
                    default: 'icon_default'
                }
            }
        }, setFixed(item) {
            //修改固定字段的值
            if (item.fixed === '1') {
                item.fixed = 'left'
            } else if (item.fixed === '2') {
                item.fixed = 'right'
            }
            if (item.align === '1') {
                item.align = 'left'
            } else if (item.align === '2') {
                item.align = 'right'
            } else if (item.align === '0') {
                item.align = 'center'
            }
        }, setProp(item) {
            item.resizable = undefined;
            if (item.sortable != undefined && item.sortable != "") {
                let order = item.field + (item.sortable == 0 ? " ASC " : " DESC ");
                this.orderByColumns.push(order)
            }
            ////时间类型
            if (!item.width && (item.selectDom == 3 || item.selectDom == 6)) {
                item.minWidth = 150
            } else if (!item.width && item.title) {
                item.minWidth = item.title.length * 30
            }
        }, setShowFooter(item) {
            if (item['totalToOtherProp']) {
                this.table['show-footer'] = true;
            }
        }, toParseOtherProp(item) {
            //其他属性赋值
            try {
                let otherProp = JSON.parse(item.otherProp)
                item.otherProp = otherProp;
                for (let key of Object.keys(otherProp)) {
                    item[key] = otherProp[key];
                }
            } catch (e) {
                if (item.otherProp) {
                    console.error(item.field + "其他属性无法解析：" + item.otherProp)
                }
                item.otherProp = {};
            }
            if (item['totalToOtherProp'] === undefined) {
                item['totalToOtherProp'] = '';
            }
        }, /**
         * 设置搜索
         * @param items
         */
        setSearchArea(items) {
            if (items.length != 0) {
                items.push({
                    itemRender: {
                        name: '$buttons', children: [{
                            props: {
                                type: 'submit', content: '查询', status: 'primary'
                            }, events: {click: this.query}
                        }, {props: {type: 'button', content: '重置'}, events: {click: this.resetQuery}}]
                    }
                })
                this.table.formConfig.size = this.table.size;
            }
            this.table.formConfig.items = items;
        }, getVNode(o, items) {
            if (o.selectType == undefined) {
                return
            }
            //99是范围查询
            if (o.selectType == 99) {
                let itemStart = this.initFormConfig(o, 5);
                let itemEnd = this.initFormConfig(o, 6);
                //时间范围查询
                if (o.selectDom == 3 || o.selectDom == 6) {
                    let placeholder = o.selectDom == 3 ? '时间' : '';
                    itemStart.placeholder = '请选择开始日期' + placeholder
                    delete itemStart.itemRender;
                    itemEnd.placeholder = '请选择结束日期' + placeholder
                }
                items.push(itemStart)
                items.push(itemEnd)
            } else {
                items.push(this.initFormConfig(o))
            }
        }, initFormConfig(o, type) {
            let key = o.fieldNameSEARCHToOtherProp != undefined && o.fieldNameSEARCHToOtherProp != '' ? o.fieldNameSEARCHToOtherProp : o.tableField;
            if (o.tableNameSEARCHToOtherProp != undefined && o.tableNameSEARCHToOtherProp != '') {
                key = o.tableNameSEARCHToOtherProp + '.' + key;
            }
            let item = {
                align: 'left',
                field: key,
                span: 6,
                searchSort: o.searchSort,
                title: o.titleSEARCHToOtherProp != undefined ? o.titleSEARCHToOtherProp : o.title,
                key: key,
                type: o.selectType,
                selectDom: o.selectDom,
                tableName: o.tableNameSEARCHToOtherProp,
                clearable: o.clearableSEARCHToOtherProp == '1' ? false : true,
                toDate: o.toDateSEARCHToOtherProp,
                itemRender: {
                    name: '$input',
                    props: {
                        placeholder: '请输入' + o.title,
                        clearable: o.clearableSEARCHToOtherProp == '1' ? false : true
                    }
                }
            };
            try {
                this.table.formConfig.data[item.key] = eval(o.valueSEARCHToOtherProp);
            } catch (e) {
            }
            if (type == 5) {
                item.title = o.title + "开始"
                item.type = 5
                item.field = "$" + o.tableField
                item.key = "$" + o.tableField
            } else if (type == 6) {
                item.field = o.tableField + "$"
                item.type = 6
                item.key = o.tableField + "$"
                item.title = o.title + "结束"
            }
            if ((item.type == 6 || item.type == 5) && o.selectDom == undefined) {
                o.selectDom = 7;
            }
            this.getItemRender(o, item, type);
            if (item.title && item.title.length > 6) {
                item.titleWidth = 20 * (item.title.length - 2);
            } else if (item.title.toString().trim().length == 0) {
                item.titleWidth = 0
            }
            if (o.spanSEARCHToOtherProp != undefined) {
                item.span = 6;
            }
            return item;
        }, getItemRender(o, item, type) {
            if (o.dictCode) {
                delete item.itemRender;
                item.slots = {default: o.selectDom + item.field}
                item.slotsName = o.selectDom + item.field
                item.options = this.dictVal(o.dictCode);
                item.placeholder = '请选择' + o.title;
                item.clearable = o.clearableSEARCHToOtherProp == '1';
                item.multiple = o.selectDom == '8';
            } else if (o.selectDom == 7) {
                item.itemRender.props.type = 'integer';
            } else if (o.selectDom == 10) {
                item.itemRender.name = 'textarea';
            } else if (o.selectDom == 3 || o.selectDom == 6) {
                delete item.itemRender;
                item.domDate = true;
                item.selectType = o.selectType;

                //这里跟element plus不一样
                //item.domFormat = version.split('.')[0] == 2 ? 'yyyy-MM-dd' : 'YYYY-MM-DD'
                item.domFormat = 'yyyy-MM-dd'
                if (item.selectDom == 3) {
                    item.domFormat = item.domFormat + ' HH:mm:ss';
                    item.domType = o.selectType == 98 ? "datetimerange" :'datetime';
                }else{
                    item.domType = o.selectType == 98 ? "daterange" :'date';
                }
                item.slots = {default: o.selectDom + item.field + "_time"}
                item.slotsName = o.selectDom + item.field + "_time"
                item.placeholder = '请选择';
                if (type == 5) {
                    item.placeholder += "开始";
                } else if (type == 6) {
                    item.placeholder += "结束";
                }
                if (o.selectDom == 3) {
                    item.placeholder += "时间";
                }
            }
        }, setColumnShowOverFlow(column, optionObj) {
            if (optionObj) {
                if (optionObj.table && optionObj.table.columnConfig && optionObj.table.columnConfig.showOverflow) {
                    if (column.type != 'seq' || column.type != 'checkbox') {
                        column.showOverflow = optionObj.table.columnConfig.showOverflow
                    }
                }
            }
        }, initMergeCells() {
            if (this.table.mergeCells) {
                this.table.mergeCells = JSON.parse(this.table.mergeCells)
                return
            }

            if (this.table.mergeFields && this.table.mergeFields.length != 0) {
                this.table.spanMethod = this.mergeRowMethod
            }
        }, // 通用行合并函数（将相同多列数据合并为一行）
        mergeRowMethod({row, _rowIndex, column, visibleData}) {
            const cellValue = row[column.field]
            if (cellValue && this.table.mergeFields.includes(column.field)) {
                const prevRow = visibleData[_rowIndex - 1]
                let nextRow = visibleData[_rowIndex + 1]
                if (prevRow && prevRow[column.field] === cellValue) {
                    return {rowspan: 0, colspan: 0}
                } else {
                    let countRowspan = 1
                    while (nextRow && nextRow[column.field] === cellValue) {
                        nextRow = visibleData[++countRowspan + _rowIndex]
                    }
                    if (countRowspan > 1) {
                        return {rowspan: countRowspan, colspan: 1}
                    }
                }
            }
        }, setDictCellStyle({row, rowIndex, $rowIndex, column, columnIndex, $columnIndex}) {
            if (column.params && column.params.cssClass) {
                return column.params.cssClass[row[column[getFiledName(column)]]];
            }
        }, setTableStyle(option) {
            if (option['cell-style'] === undefined) {
                option['cell-style'] = {
                    flag: "flag##function#", isFunction: true
                }
            }
            option['cell-style']['code'] = "let OTMixinColumnMethod_setDictCellStyle = this.setDictCellStyle(params); if(OTMixinColumnMethod_setDictCellStyle){ return OTMixinColumnMethod_setDictCellStyle;}\n" + option['cell-style']['code'];
        },
    }
}
